package com.atuguigu.boot3.core.pingjia;

import java.util.Arrays;
import java.util.List;

// 完整的模糊评估系统
public class FuzzyEvaluationSystem {
    private List<Indicator> indicators;
    private List<Evaluation> evaluations;
    private double[][] fuzzyMatrix;

    public FuzzyEvaluationSystem(List<Indicator> indicators,
                                 List<Evaluation> evaluations) {
        this.indicators = indicators;
        this.evaluations = evaluations;
        this.fuzzyMatrix = new double[indicators.size()][evaluations.size()];
    }

    // 设置模糊矩阵
    public void setFuzzyMatrix(double[][] matrix) {
        if (matrix.length != indicators.size() ||
                matrix[0].length != evaluations.size()) {
            throw new IllegalArgumentException("矩阵维度不匹配");
        }
        this.fuzzyMatrix = matrix;
    }

    // 验证权重总和为1
    private boolean validateWeights() {
        double sum = indicators.stream()
                .mapToDouble(Indicator::getWeight)
                .sum();
        return Math.abs(sum - 1.0) < 0.001;
    }

    // 执行评估
    public double evaluate() {
        if (!validateWeights()) {
            throw new IllegalStateException("权重总和必须为1");
        }

        double[] weights = indicators.stream()
                .mapToDouble(Indicator::getWeight)
                .toArray();

        // 计算 B = A * R
        double[] B = new double[evaluations.size()];
        for (int j = 0; j < evaluations.size(); j++) {
            for (int i = 0; i < indicators.size(); i++) {
                B[j] += weights[i] * fuzzyMatrix[i][j];
            }
        }

        // 归一化
        double sumB = Arrays.stream(B).sum();
        double[] normalizedB = Arrays.stream(B)
                .map(b -> b / sumB)
                .toArray();

        // 计算最终得分
        double finalScore = 0;
        for (int i = 0; i < evaluations.size(); i++) {
            finalScore += normalizedB[i] * evaluations.get(i).getScore();
        }

        return finalScore;
    }
}